/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.model.actor.instance;

import jmmos.Config;
import jmmos.gameserver.ai.CtrlIntention;
import jmmos.gameserver.ai.MMOCharacterAI;
import jmmos.gameserver.ai.MMOFortSiegeGuardAI;
import jmmos.gameserver.ai.MMOSiegeGuardAI;
import jmmos.gameserver.ai.MMOSpecialSiegeGuardAI;
import jmmos.gameserver.instancemanager.CastleManager;
import jmmos.gameserver.instancemanager.FortManager;
import jmmos.gameserver.instancemanager.TerritoryWarManager;
import jmmos.gameserver.model.MMOCharPosition;
import jmmos.gameserver.model.actor.MMOAttackable;
import jmmos.gameserver.model.actor.MMOCharacter;
import jmmos.gameserver.model.actor.MMOPlayable;
import jmmos.gameserver.model.actor.knownlist.DefenderKnownList;
import jmmos.gameserver.model.actor.templates.MMONpcTemplate;
import jmmos.gameserver.model.entity.Castle;
import jmmos.gameserver.model.entity.Fort;
import jmmos.gameserver.model.entity.guildhall.SiegableHall;
import jmmos.gameserver.network.serverpackets.ActionFailed;
import jmmos.gameserver.network.serverpackets.MyTargetSelected;
import jmmos.gameserver.network.serverpackets.StatusUpdate;
import jmmos.gameserver.network.serverpackets.ValidateLocation;

public class MMODefenderInstance extends MMOAttackable
{
	private Castle _castle = null; // the castle which the instance should defend
	private Fort _fort = null; // the fortress which the instance should defend
	private SiegableHall _hall = null; // the siegable hall which the instance should defend
	
	public MMODefenderInstance(int objectId, MMONpcTemplate template)
	{
		super(objectId, template);
		setInstanceType(InstanceType.MMODefenderInstance);
	}
	
	@Override
	public DefenderKnownList getKnownList()
	{
		return (DefenderKnownList) super.getKnownList();
	}
	
	@Override
	public void initKnownList()
	{
		setKnownList(new DefenderKnownList(this));
	}
	
	@Override
	public MMOCharacterAI getAI()
	{
		MMOCharacterAI ai = _ai; // copy handle
		if (ai == null)
		{
			synchronized (this)
			{
				if (_ai == null)
				{
					if ((getConquerableHall() == null) && (getCastle(10000) == null))
					{
						_ai = new MMOFortSiegeGuardAI(new AIAccessor());
					}
					else if (getCastle(10000) != null)
					{
						_ai = new MMOSiegeGuardAI(new AIAccessor());
					}
					else
					{
						_ai = new MMOSpecialSiegeGuardAI(new AIAccessor());
					}
				}
				return _ai;
			}
		}
		return ai;
	}
	
	/**
	 * Return True if a siege is in progress and the MMOCharacter attacker isn't a Defender.
	 * @param attacker The MMOCharacter that the MMOSiegeGuardInstance try to attack
	 */
	@Override
	public boolean isAutoAttackable(MMOCharacter attacker)
	{
		// Attackable during siege by all except defenders
		if (!(attacker instanceof MMOPlayable))
		{
			return false;
		}
		
		MMOPcInstance player = attacker.getActingPlayer();
		
		// Check if siege is in progress
		if (((_fort != null) && _fort.getZone().isActive()) || ((_castle != null) && _castle.getZone().isActive()) || ((_hall != null) && _hall.getSiegeZone().isActive()))
		{
			int activeSiegeId = (_fort != null ? _fort.getFortId() : (_castle != null ? _castle.getCastleId() : (_hall != null ? _hall.getId() : 0)));
			
			// Check if player is an enemy of this defender npc
			if ((player != null) && (((player.getSiegeState() == 2) && !player.isRegisteredOnThisSiegeField(activeSiegeId)) || ((player.getSiegeState() == 1) && !TerritoryWarManager.getInstance().isAllyField(player, activeSiegeId)) || (player.getSiegeState() == 0)))
			{
				return true;
			}
		}
		return false;
	}
	
	@Override
	public boolean hasRandomAnimation()
	{
		return false;
	}
	
	/**
	 * This method forces guard to return to home location previously set
	 */
	@Override
	public void returnHome()
	{
		if (getWalkSpeed() <= 0)
		{
			return;
		}
		if (getSpawn() == null)
		{
			return;
		}
		if (!isInsideRadius(getSpawn().getLocx(), getSpawn().getLocy(), 40, false))
		{
			if (Config.DEBUG)
			{
				_log.info(getObjectId() + ": moving home");
			}
			setisReturningToSpawnPoint(true);
			clearAggroList();
			
			if (hasAI())
			{
				getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new MMOCharPosition(getSpawn().getLocx(), getSpawn().getLocy(), getSpawn().getLocz(), 0));
			}
		}
	}
	
	@Override
	public void onSpawn()
	{
		super.onSpawn();
		
		_fort = FortManager.getInstance().getFort(getX(), getY(), getZ());
		_castle = CastleManager.getInstance().getCastle(getX(), getY(), getZ());
		_hall = getConquerableHall();
		if ((_fort == null) && (_castle == null) && (_hall == null))
		{
			_log.warning("MMODefenderInstance spawned outside of Fortress, Castle or Siegable hall Zone! NpcId: " + getNpcId() + " x=" + getX() + " y=" + getY() + " z=" + getZ());
		}
	}
	
	/**
	 * Custom onAction behaviour. Note that super() is not called because guards need extra check to see if a player should interact or ATTACK them when clicked.
	 */
	@Override
	public void onAction(MMOPcInstance player, boolean interact)
	{
		if (!canTarget(player))
		{
			player.sendPacket(ActionFailed.STATIC_PACKET);
			return;
		}
		
		// Check if the MMOPcInstance already target the MMONpcInstance
		if (this != player.getTarget())
		{
			if (Config.DEBUG)
			{
				_log.info("new target selected:" + getObjectId());
			}
			
			// Set the target of the MMOPcInstance player
			player.setTarget(this);
			
			// Send a Server->Client packet MyTargetSelected to the MMOPcInstance player
			MyTargetSelected my = new MyTargetSelected(getObjectId(), player.getLevel() - getLevel());
			player.sendPacket(my);
			
			// Send a Server->Client packet StatusUpdate of the MMONpcInstance to the MMOPcInstance to update its HP bar
			StatusUpdate su = new StatusUpdate(this);
			su.addAttribute(StatusUpdate.CUR_HP, (int) getStatus().getCurrentHp());
			su.addAttribute(StatusUpdate.MAX_HP, getMaxHp());
			player.sendPacket(su);
			
			// Send a Server->Client packet ValidateLocation to correct the MMONpcInstance position and heading on the client
			player.sendPacket(new ValidateLocation(this));
		}
		else if (interact)
		{
			if (isAutoAttackable(player) && !isAlikeDead())
			{
				if (Math.abs(player.getZ() - getZ()) < 600) // this max heigth difference might need some tweaking
				{
					player.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, this);
				}
			}
			if (!isAutoAttackable(player))
			{
				if (!canInteract(player))
				{
					// Notify the MMOPcInstance AI with AI_INTENTION_INTERACT
					player.getAI().setIntention(CtrlIntention.AI_INTENTION_INTERACT, this);
				}
			}
		}
		// Send a Server->Client ActionFailed to the MMOPcInstance in order to avoid that the client wait another packet
		player.sendPacket(ActionFailed.STATIC_PACKET);
	}
	
	@Override
	public void addDamageHate(MMOCharacter attacker, int damage, int aggro)
	{
		if (attacker == null)
		{
			return;
		}
		
		if (!(attacker instanceof MMODefenderInstance))
		{
			if ((damage == 0) && (aggro <= 1) && (attacker instanceof MMOPlayable))
			{
				MMOPcInstance player = attacker.getActingPlayer();
				// Check if siege is in progress
				if (((_fort != null) && _fort.getZone().isActive()) || ((_castle != null) && _castle.getZone().isActive()) || ((_hall != null) && _hall.getSiegeZone().isActive()))
				{
					int activeSiegeId = (_fort != null ? _fort.getFortId() : (_castle != null ? _castle.getCastleId() : (_hall != null ? _hall.getId() : 0)));
					if ((player != null) && (((player.getSiegeState() == 2) && player.isRegisteredOnThisSiegeField(activeSiegeId)) || ((player.getSiegeState() == 1) && TerritoryWarManager.getInstance().isAllyField(player, activeSiegeId))))
					{
						return;
					}
				}
			}
			super.addDamageHate(attacker, damage, aggro);
		}
	}
}